import * as fs from 'fs';
import * as path from 'path';
import {isExist} from "../unit";



function defaultCallback(resolve, reject){
    return function cb(err){
        if(err){
            reject(err);
        }
        resolve(true);
    }
}


/**
 * @param resolve
 * @param reject
 * @param _data 编码后的数据
 * */
function writeDefaultCallback(resolve, reject, _data){
    return function cb(err){
        if(err){
            reject(err);
        }
        resolve(_data);
    }
}


export default class WriteFile{
    _buffer = Buffer.alloc(0);
    _offset:number = 0;
    //一次最多分配多少内存合适?
    MAX_BYTES_LENGTH = 1024;
    constructor(){}

    stringToUnit8Array(text:string){
        let _textArray = text.split('');
        // utf8中文字符占用3字节
        const BYTE_LENGTH = 3;
        let buf = Buffer.alloc(_textArray.length * BYTE_LENGTH);
        buf.write(text);
        return buf;
    }
    /**
     * @param fileName {string} 文件路径与文件名:./test1/a.txt
     * @param data 要写入到文件中的数据
     * @param callback
     * */
    write(fileName:string, data:string, callback=writeDefaultCallback){
        fileName = path.resolve(fileName);
        console.log('write');
        let _data:Buffer;
        if(!Buffer.isBuffer(data)){
            _data = this.stringToUnit8Array(data);
        }
        console.log('write2');
        return new Promise(
            (resolve, reject)=>{
              return fs.writeFile(fileName, _data, callback.call(null, resolve, reject, _data));
        });
    }


    static unlinkFile(fileName:string){
        fileName = path.resolve(fileName);
        if(isExist(fileName)){
            fs.unlink(fileName,(err)=>{
                if(err){
                    throw err;
                }
            });
        }
    }

}